package org.docx4j.utils;

/**
 * 矩形旋转工具类
 * 于吉宽 add这个类，旋转图片
 */
public class RotatedDimensionUtil {

    private static final int FULL_CIRCLE_DEGREES = 360;

    /**
     * 计算矩形旋转后的新尺寸
     *
     * @param w 矩形原始宽度
     * @param h 矩形原始高度
     * @param angle 旋转角度（度数）
     * @return 包含两个元素的数组，第一个元素是旋转后的宽度，第二个元素是旋转后的高度
     * @throws IllegalArgumentException 如果宽或高为负值
     */
    public static int[] getRotatedDimensions(int w, int h, int angle) {
        if (w < 0 || h < 0) {
            throw new IllegalArgumentException("Width and height must be non-negative.");
        }

        // Normalize angle to [0, 360)
        angle = normalizeAngle(angle);

        // Handle common right-angle rotations directly
        if (angle == 0 || angle == 180) {
            return new int[]{w, h};
        } else if (angle == 90 || angle == 270) {
            return new int[]{h, w};
        }

        // For arbitrary angles, use trigonometric computation
        double radians = Math.toRadians(angle);
        double sinValue = Math.abs(Math.sin(radians));
        double cosValue = Math.abs(Math.cos(radians));

        long newWidth = (long) Math.round(w * cosValue + h * sinValue);
        long newHeight = (long) Math.round(w * sinValue + h * cosValue);

        // Clamp to Integer.MAX_VALUE to prevent overflow during cast
        return new int[]{
                (int) Math.min(newWidth, Integer.MAX_VALUE),
                (int) Math.min(newHeight, Integer.MAX_VALUE)
        };
    }

    /**
     * Normalize angle to be within [0, 360)
     */
    private static int normalizeAngle(int angle) {
        int normalized = angle % FULL_CIRCLE_DEGREES;
        if (normalized < 0) {
            normalized += FULL_CIRCLE_DEGREES;
        }
        return normalized;
    }
}
